﻿namespace RegattaStarter
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;
    using Microsoft.Phone.Controls;
    using System.Diagnostics;
    using System.Windows.Threading;
    using Microsoft.Phone.Shell;

    public partial class MainPage : PhoneApplicationPage
    {
        #region Common Objects

        /// <summary>
        /// Instance of the timer for the regatta.
        /// </summary>
        public static DispatcherTimer raceTimer;

        /// <summary>
        /// TimePicker timer.
        /// </summary>
        public static DispatcherTimer timePickerTimer;

        /// <summary>
        /// Specifies who is calling the valueChange of the timepicker.
        /// </summary>
        public static string senderName;

        /// <summary>
        /// Uri used for change the images.
        /// </summary>
        public Uri imgUri;

        /// <summary>
        /// List of url.
        /// </summary>
        public List<string> flags;

        /// <summary>
        /// I set up counter = 300 because we will count 5 minutes.
        /// 60 seconds * 5.
        /// </summary>
        int counter = 300;

        #endregion 

        #region Utility Methods

        /// <summary>
        /// Stops the racetimer and set it to null.
        /// </summary>
        private void InitializeRacingTimer()
        {
            if (raceTimer != null)
            {
                raceTimer.Stop();
                raceTimer = null;
            }

            counter = 300;
            senderName = "initialize";
            this.EventTimePicker.Value = null;
            senderName = string.Empty;
            this.StopWatchBox.IsEnabled = false;
            TimeSpan stopWatch = new TimeSpan(0, 5, 0);
            this.StopWatchBox.Text = stopWatch.ToString();

            imgUri = new Uri("/Images/Avanade_logo.png", UriKind.Relative);
            ImageBox.Source = new System.Windows.Media.Imaging.BitmapImage(imgUri);

            ApplicationBarIconButton btnStart = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
            ApplicationBarIconButton btnPause = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
            ApplicationBarIconButton btnClear = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
            btnStart.IsEnabled = true;
            btnPause.IsEnabled = false;
            btnClear.IsEnabled = false;

            flags = SettingsMethods.GetFlags(SettingsMethods.GetUserDefault());
        }

        /// <summary>
        /// Stops the racetimer and set it to null.
        /// </summary>
        private void SetAutomaticRacingTimer()
        {
            if (timePickerTimer != null)
            {
                timePickerTimer.Stop();
                timePickerTimer = null;
            }

            if (raceTimer != null)
            {
                raceTimer.Stop();
                raceTimer = null;
            }

            timePickerTimer = new DispatcherTimer();
            timePickerTimer.Tick += new EventHandler(timePickerTimer_Tick);
            timePickerTimer.Interval = new TimeSpan(0, 0, 1);

            counter = 300;
            senderName = string.Empty;
            this.StopWatchBox.IsEnabled = false;
            TimeSpan stopWatch = new TimeSpan(0, 5, 0);
            this.StopWatchBox.Text = stopWatch.ToString();

            imgUri = new Uri("/Images/Avanade_logo.png", UriKind.Relative);
            ImageBox.Source = new System.Windows.Media.Imaging.BitmapImage(imgUri);

            ApplicationBarIconButton btnStart = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
            ApplicationBarIconButton btnPause = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
            ApplicationBarIconButton btnClear = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
            btnStart.IsEnabled = true;
            btnPause.IsEnabled = false;
            btnClear.IsEnabled = false;

            timePickerTimer.Start();
        }

        /// <summary>
        /// Returns a list of url for the flags.
        /// NOW IS FAKE. I HAVE TO IMPLEMENT USING AN APPCONFING FOR SAVING CHANGES FROM THE USER AND CREATING A DEFAULT CONFIGURATION.
        /// </summary>
        /// <returns>A list of url for the flags.</returns>
        private List<string> getFlags()
        {
            flags = new List<string>();

            string avanadeLogoUrl = "/Images/Avanade_Logo.png";
            string firstFlag = "/Images/Flags/Papa_Flag.png";
            string secondFlag = "/Images/Flags/Oscar_Flag.png";
            string thirdFlag = "/Images/Flags/Romeo_Flag.png";

            flags.Add(firstFlag);
            flags.Add(secondFlag);
            flags.Add(thirdFlag);
            flags.Add(avanadeLogoUrl);

            return flags;
        }

        #endregion

        #region MainPage Management

        /// <summary>
        /// Constructor of MainPage.
        /// </summary>
        public MainPage()
        {
            InitializeComponent();
            senderName = "main";
            InitializeRacingTimer();
        }

        #endregion

        #region Tick

        /// <summary>
        /// Raise every tick.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void raceTimer_Tick(object sender, EventArgs e)
        {
            TimeSpan stopWatchTime = TimeSpan.Parse(StopWatchBox.Text);
            stopWatchTime = stopWatchTime.Subtract(new TimeSpan(0, 0, 1));
            this.StopWatchBox.Text = stopWatchTime.ToString();

            switch (counter) 
            {
                case 300:
                        imgUri = new Uri(flags[0], UriKind.Relative);
                        ImageBox.Source = new System.Windows.Media.Imaging.BitmapImage(imgUri);
                    break;
                case 240:
                        imgUri = new Uri(flags[1], UriKind.Relative);
                        ImageBox.Source = new System.Windows.Media.Imaging.BitmapImage(imgUri);
                    break;
                case 60:
                        imgUri = new Uri(flags[2], UriKind.Relative);
                        ImageBox.Source = new System.Windows.Media.Imaging.BitmapImage(imgUri);
                    break;
                case 0:
                        imgUri = new Uri(flags[3], UriKind.Relative);
                        ImageBox.Source = new System.Windows.Media.Imaging.BitmapImage(imgUri);
                    InitializeRacingTimer();
                    break;
                default:
                    break;
            }

            counter--;
        }

        #endregion

        #region Override of Back Key

        /// <summary>
        /// Override the OnBackKeyPress.
        /// Used to force the user to be sure to close the application.
        /// </summary>
        /// <param name="e"></param>
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            MessageBoxResult resultBox = MessageBox.Show("Are you sure you want to exit the application?", "Application Exit", MessageBoxButton.OKCancel);
            if (resultBox == MessageBoxResult.OK)
            {
                base.OnBackKeyPress(new System.ComponentModel.CancelEventArgs());
            }
            else 
            {
                e.Cancel = true;
            }
        }

        #endregion

        #region Event Handler of TimePicker

        /// <summary>
        /// Gets the value of the time inserted.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">Object of type <see cref="DateTimeValueChangedEventArgs"/>.</param>
        private void TimePicker_ValueChanged(object sender, DateTimeValueChangedEventArgs e)
        {
            var time = (DateTime?)EventTimePicker.Value;

            if (senderName.Equals(string.Empty)) 
            {
                SetAutomaticRacingTimer();
            }
         }

        /// <summary>
        /// Evento Tick del timepickertimer.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void timePickerTimer_Tick(object sender, EventArgs e)
        {
            var time = (DateTime?)EventTimePicker.Value;
            var now = DateTime.Now;

            if (time.Value.Hour == now.Hour) 
            {
                if (time.Value.Minute == now.Minute) 
                {
                    timePickerTimer.Stop();
                    timePickerTimer = null;
                    raceTimer = new DispatcherTimer();
                    raceTimer.Tick += new EventHandler(raceTimer_Tick);
                    raceTimer.Interval = new TimeSpan(0, 0, 1);

                    ApplicationBarIconButton btnStart = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
                    ApplicationBarIconButton btnPause = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
                    ApplicationBarIconButton btnClear = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
                    btnStart.IsEnabled = false;
                    btnPause.IsEnabled = true;
                    btnClear.IsEnabled = true;

                    raceTimer.Start();
                }
            }
        }

        #endregion

        #region Event Handler related to AppBar

        /// <summary>
        /// Starts the stopWatch for the regatta.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AppBarStart_Click(object sender, EventArgs e)
        {
            var time = (DateTime?)EventTimePicker.Value;
            if (time == null)
            {
                senderName = "start";
                EventTimePicker.Value = DateTime.Now;
                senderName = string.Empty;
                raceTimer = new DispatcherTimer();
                raceTimer.Tick += new EventHandler(raceTimer_Tick);
                raceTimer.Interval = new TimeSpan(0, 0, 1);
                raceTimer.Start();
            }

            if (raceTimer != null && (!raceTimer.IsEnabled)) 
            {
                raceTimer.Start();
            }

            if (timePickerTimer != null) 
            {
                timePickerTimer.Stop();
                timePickerTimer = null;
                senderName = "start";
                EventTimePicker.Value = DateTime.Now;
                senderName = string.Empty;
                raceTimer = new DispatcherTimer();
                raceTimer.Tick += new EventHandler(raceTimer_Tick);
                raceTimer.Interval = new TimeSpan(0, 0, 1);
                raceTimer.Start();
            }

            ApplicationBarIconButton btnStart = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
            ApplicationBarIconButton btnPause = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
            ApplicationBarIconButton btnClear = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
            btnStart.IsEnabled = false;
            btnPause.IsEnabled = true;
            btnClear.IsEnabled = true;
        }

        /// <summary>
        /// Pause the stopWatch for the regatta.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AppBarPause_Click(object sender, EventArgs e)
        {
            if (raceTimer != null && (raceTimer.IsEnabled))
            {
                raceTimer.Stop();
            }

            ApplicationBarIconButton btnStart = (ApplicationBarIconButton)ApplicationBar.Buttons[0];
            ApplicationBarIconButton btnPause = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
            ApplicationBarIconButton btnClear = (ApplicationBarIconButton)ApplicationBar.Buttons[2];
            btnStart.IsEnabled = true;
            btnPause.IsEnabled = false;
            btnClear.IsEnabled = true;
        }

        /// <summary>
        /// Clear the racing timer.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AppBarClear_Click(object sender, EventArgs e)
        {
            if (raceTimer != null)
            {
                InitializeRacingTimer();
            }
        }

        /// <summary>
        /// Handle the Click on MenuItem Setting in the ApplicationBar.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Settings_Click(object sender, EventArgs e)
        {
            SettingsMethods.SaveUseDefault(true);
            this.NavigationService.Navigate(new Uri("/Settings.xaml", UriKind.Relative));
        }

        /// <summary>
        ///  Handle the Click on MenuItem About in the ApplicationBar.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void About_Click(object sender, EventArgs e)
        {
            this.NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
        }

        #endregion
    }
}